package com.smallbug.longman;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Build;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;


import com.smallbug.longman.adapter.SenseAdapter;
import com.smallbug.longman.bean.EXAMPLE;
import com.smallbug.longman.bean.Entry;
import com.smallbug.longman.bean.HEAD;
import com.smallbug.longman.bean.Sense;
import com.smallbug.longman.bean.Subsense;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Locale;

public class ShowWord extends AppCompatActivity {

    ScrollView scrollView;

    TextView txtEnP, txtArP;

    ImageButton shBtnShare, shBtnCopy, shBtnAPlus, shBtnAMinus, shBtnNext, shBtnPrev;

    Button btnSpeechUS, btnSpeechUK;

    ToggleButton tbtnFav;

    SharedPreferences settings;

    int id, adSho;

    Cursor cursor;

    sqlHelper sqlHelper;

    TextToSpeech tts;

    Toolbar toolbar;
    private RecyclerView SenseRecyclerView;
    private SenseAdapter senseAdapter;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_show_word);
        initialize();
        listener();
        sql();
    }

    private void initialize() {
        toolbar = (Toolbar) findViewById(R.id.toolbar_showWords);
        if (getIntent().hasExtra("title")){
            title = this.getIntent().getExtras().getString("title");
            toolbar.setTitle(title);
        }
        setSupportActionBar(toolbar);
        id = this.getIntent().getExtras().getInt("id");
        scrollView = (ScrollView) findViewById(R.id.scrollView);

        txtEnP = (TextView) findViewById(R.id.txtEnP);
        txtArP = (TextView) findViewById(R.id.txtArP);

        shBtnShare = (ImageButton) findViewById(R.id.shBtnShare);
        shBtnCopy = (ImageButton) findViewById(R.id.shBtnCopy);
        shBtnAPlus = (ImageButton) findViewById(R.id.shBtnAPlus);
        shBtnAMinus = (ImageButton) findViewById(R.id.shBtnAMinus);

        shBtnNext = (ImageButton) findViewById(R.id.shBtnNext);
        shBtnPrev = (ImageButton) findViewById(R.id.shBtnPrev);

        btnSpeechUK = (Button) findViewById(R.id.btnSpeechUK);
        btnSpeechUS = (Button) findViewById(R.id.btnSpeechUS);

        tbtnFav = (ToggleButton) findViewById(R.id.tbtnFav);
        SenseRecyclerView=(RecyclerView)findViewById(R.id.SenseRecyclerView);
        SenseRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL,false){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        senseAdapter=new SenseAdapter(ShowWord.this);
        SenseRecyclerView.setAdapter(senseAdapter);

        settings = getSharedPreferences("settings", MODE_PRIVATE);

        txtEnP.setTextSize(TypedValue.COMPLEX_UNIT_PX, settings.getFloat("text_size", 45));
        txtArP.setTextSize(TypedValue.COMPLEX_UNIT_PX, settings.getFloat("text_size", 45));

        sqlHelper = new sqlHelper(this);
        adSho = 0;
    }


    public void listener() {

        shBtnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String word;
                String[] arr = txtEnP.getText().toString().split(" ");
                word = arr[0];
                Intent share = new Intent(Intent.ACTION_SEND);
                share.setType("text/plain");
                share.putExtra(Intent.EXTRA_TEXT, word);
                startActivity(Intent.createChooser(share, "Word sharing by :"));
            }
        });

        ///////

        shBtnCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String word;
                String[] arr = txtEnP.getText().toString().split(" ");
                word = arr[0];
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                clipboardManager.setPrimaryClip(ClipData.newPlainText("Word", word));
                Toast.makeText(ShowWord.this, "Copied", Toast.LENGTH_LONG).show();
            }
        });

        ///////

        shBtnAPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (txtEnP.getTextSize() >= 70)
                    Toast.makeText(ShowWord.this, "This is the largest possible size !!", Toast.LENGTH_LONG).show();
                else {
                    txtEnP.setTextSize(TypedValue.COMPLEX_UNIT_PX,  txtEnP.getTextSize() + 5);
                    settings.edit().putFloat("text_size", txtEnP.getTextSize()).apply();
                    senseAdapter.setTextSize(1);
                }
            }
        });

        ////////

        shBtnAMinus.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (txtEnP.getTextSize() <= 25)
                    Toast.makeText(ShowWord.this, "This is as smallest possible size!!", Toast.LENGTH_LONG).show();
                else {
                    txtEnP.setTextSize(TypedValue.COMPLEX_UNIT_PX,  txtEnP.getTextSize() - 5);
                    settings.edit().putFloat("text_size", txtEnP.getTextSize()).apply();
                    senseAdapter.setTextSize(2);
                }
            }
        });


        tbtnFav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tbtnFav.isChecked()) {
                    sqlHelper.openDataBase();
                    sqlHelper.addToFav(id);
                    sqlHelper.close();
                    Toast.makeText(ShowWord.this, "Added to saved words", Toast.LENGTH_SHORT).show();
                } else {
                    sqlHelper.openDataBase();
                    sqlHelper.removeFromFav(id);
                    Toast.makeText(ShowWord.this, "Removed from saved words", Toast.LENGTH_SHORT).show();
                    sqlHelper.close();
                }
            }
        });


        /**** ****/
        shBtnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sqlHelper.openDataBase();
                if (id == sqlHelper.getNum())
                    Toast.makeText(ShowWord.this, "The last word in the list", Toast.LENGTH_SHORT).show();
                else {
                    id++;
                    refresh();
                }
                sqlHelper.close();
            }
        });

        shBtnPrev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sqlHelper.openDataBase();
                if (id == 1)
                    Toast.makeText(ShowWord.this, "First word in the list", Toast.LENGTH_SHORT).show();
                else {
                    id--;
                    refresh();
                }
                sqlHelper.close();
            }
        });


        btnSpeechUS.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tts = new TextToSpeech(ShowWord.this, new TextToSpeech.OnInitListener() {
                    @Override
                    public void onInit(int status) {

                        if (status == TextToSpeech.SUCCESS) {
                            tts.setLanguage(Locale.US);
                            String[] arr = txtEnP.getText().toString().split(" ");
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                                tts.speak(arr[0], TextToSpeech.QUEUE_FLUSH, null, null);
                            else
                                tts.speak(arr[0], TextToSpeech.QUEUE_FLUSH, null);
                        }
                    }
                });
            }
        });

        btnSpeechUK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tts = new TextToSpeech(ShowWord.this, new TextToSpeech.OnInitListener() {
                    @Override
                    public void onInit(int status) {

                        if (status == TextToSpeech.SUCCESS) {
                            tts.setLanguage(Locale.US);
                            String[] arr = txtEnP.getText().toString().split(" ");
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                tts.speak(arr[0], TextToSpeech.QUEUE_ADD, null, null);
                            }
                            tts.setSpeechRate(2);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                            {
                                for(int start = 0; start < arr[0].length(); start++)
                                {
                                    tts.speak(arr[0].substring(start,  start + 1), TextToSpeech.QUEUE_ADD, null, null);
                                }
                                tts.setSpeechRate(1);
                                tts.speak(arr[0], TextToSpeech.QUEUE_ADD, null, null);
                            }
                            else
                            {
                                tts.speak(arr[0].substring(0, 1), TextToSpeech.QUEUE_FLUSH, null);
                            }

                        }
                    }
                });
            }
        });


    }

    public void showScroll() {
        scrollView.animate().alpha(1.0f).setDuration(500).start();
    }

    public void hideScroll() {
        scrollView.animate().alpha(0.0f).setDuration(500).start();

    }

    public void refresh() {
        hideScroll();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                showScroll();
                sql();
            }
        }, 500);
        adSho++;
        if (adSho % 6 == 0) {
            //refreshAds();
        }
    }


    private void sql() {
        cursor = null;
        sqlHelper.openDataBase();
        cursor = sqlHelper.getData(id);
        if (cursor.moveToFirst() && cursor != null) {
            txtEnP.setText(cursor.getString(1));
            toolbar.setTitle(cursor.getString(1));
            //这里是判断是不是收藏的单词，目前数据库无此字段
        /*    if (cursor.getInt(3) == 1)
                tbtnFav.setChecked(true);
            else
                tbtnFav.setChecked(false);*/
            //2位置代表的是entry_id,获取到后到content表里面查找内容,为xml格式
            String entry_id = cursor.getString(2);
            Cursor contentCursor = sqlHelper.getContentData(entry_id);
            if (contentCursor.moveToFirst() && contentCursor != null) {
                String contentXml=contentCursor.getString(1);
               dom4j(contentXml);
            }
        }
    }
    private void dom4j(String xml){

        //读取xml，封装对象
        SAXReader saxReader =new SAXReader();
        Document doc= null;
        try {
            doc = saxReader.read(new ByteArrayInputStream(xml.getBytes()));
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        Element elem=doc.getRootElement();

            Entry entry=new Entry();
            entry.setEntryId(elem.elementText("EntryId"));  //读取文本
            entry.setEntryIdmId(elem.elementText("EntryIdmId"));

            Element headElem = elem.element("Head");
                HEAD head=new HEAD();
                head.setAudio_GB_HWD_PRON(headElem.elementText("Audio_GB_HWD_PRON"));
                head.setAudio_US_HWD_PRON(headElem.elementText("Audio_US_HWD_PRON"));
                head.setBASE1(headElem.elementText("BASE1"));
                head.setBASE2(headElem.elementText("BASE2"));
                head.setILLUSTRATION(headElem.elementText("ILLUSTRATION"));
                entry.setHead( head );

            Element asdasd = elem.element("Senses");
            ArrayList<Sense> sense=new ArrayList();
            Iterator<Element> senseIt= asdasd.elementIterator("Sense");
            while(senseIt.hasNext()) {
                Element senses = senseIt.next();
                Sense a=new Sense();
                a.setDEF(senses.elementText("DEF"));
                a.setAudio_SFX(senses.elementText("Audio_SFX"));
                a.setILLUSTRATION(senses.elementText("ILLUSTRATION"));
                a.setSenseId(senses.elementText("SenseId"));
                a.setSensenum(senses.elementText("sensenum"));

                if ( senses.element("Examples")!=null){
                    Iterator<Element> exampleIt = senses.element("Examples").elementIterator("EXAMPLE");
                    ArrayList<EXAMPLE> examples=new ArrayList();
                    while(exampleIt.hasNext()) {
                        Element example=exampleIt.next();
                        EXAMPLE b=new EXAMPLE();
                        b.setBASE(example.elementText("BASE"));
                        b.setAudio_EXA_PRON(example.elementText("Audio_EXA_PRON"));
                        b.setExampleId(example.elementText("ExampleId"));
                        examples.add(b);
                    }
                    a.setExamples(examples);
                }


                if (senses.element("Subsenses")!=null){
                    Iterator<Element> SubsensesIt = senses.element("Subsenses").elementIterator("Subsense");
                    ArrayList<Subsense> subsenses=new ArrayList();
                    while(SubsensesIt.hasNext()) {
                        Element subsense=SubsensesIt.next();
                        Subsense c=new Subsense();
                        c.setDEF(subsense.elementText("DEF"));
                        c.setSenseId(subsense.elementText("SenseId"));
                        c.setSensenum(subsense.elementText("sensenum"));

                        if (subsense.element("Examples")!=null){
                            Iterator<Element> exampleIt2 = subsense.element("Examples").elementIterator("EXAMPLE");
                            ArrayList<EXAMPLE> examples2=new ArrayList();
                            while(exampleIt2.hasNext()) {
                                Element example=exampleIt2.next();
                                EXAMPLE b=new EXAMPLE();
                                b.setBASE(example.elementText("BASE"));
                                b.setAudio_EXA_PRON(example.elementText("Audio_EXA_PRON"));
                                b.setExampleId(example.elementText("ExampleId"));
                                examples2.add(b);
                            }
                            c.setExamples(examples2);
                        }
                        subsenses.add(c);
                    }
                    a.setSubsenses(subsenses);
                }
                sense.add(a);
            }
            entry.setSenses(sense);
        setContentData(entry);
    }
    private void setContentData(Entry entry){
        senseAdapter.setData(entry.getSenses());
    }

    @Override
    protected void onPause() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
                Intent intent=new Intent();
                String name=toolbar.getTitle().toString();
                Log.e("asd",name);
                intent.putExtra("name",toolbar.getTitle().toString());
                setResult(11,intent);
                finish();
                return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }
}
